import useForm from '@module/useForm'
import './styles.css'
import usePartState from "@module/usePartState";
import Rest from "@module/Rest";
import ZenModal from "@root/components/ZenUI/ZenModal/ZenModal";
import AddFile from "../AddFile/AddFile"
import InputItem from "../InputItem/InputItem"
import TextAreaItem from "../TextAreaItem/TextAreaItem"
import ModalContent from '../ModalContent/ModalContent'
import ConfirmPriceModal from './ConfirmPriceModal'
import BidProInfo from './BidProInfo'
import ChoosePro from './ChoosePro'
import InfoModal from "@root/pages/ruijing/common/modal/InfoModal"
import RobinFilter from '@module/RobinFilter'
import EventApi from '@module/EventApi'
import Form from '@ui/RJMart/form'
import Filter from "@module/Filter";
import urlHook from "@page/common/utils/urlHook";



let infoModal=null;
export default function InputBid(props) {
    const info=props.info||{};
    const {bid,items,}=info;
    const {isEditPage,isSelected,}=props;

    // console.log('jxxx123123')
    const [stateObj, updateState] = usePartState({
        showEmityTips1:false,
        showEmityTips2:false,
        showEmityTips3:false,
        emityTipArr:[],
        defaultPrice:'',
        modalMsg:'请选择商品',
        // refresh:false
        // isAutoSet:false
    });
    const defaultEmiptyTips=['此项为必填项','此项为必填项','此项为必填项']
    const {showEmityTips1,showEmityTips2,showEmityTips3,emityTipArr,modalMsg,defaultPrice}=stateObj;
    const bidInfo=props.isSelected? props.bidInfo:bid
    // let isAutoSet=false

    function doSubmit() {

    }

    const {
        formData,
        handleChange,
        handleSubmit,
        updateFormData,
        validations,
        addValidate,
        addValidateMulti
    } = useForm(doSubmit, {}, "bidInputForm");
    
    // console.log(formData)


    React.useEffect(()=>{
        // console.log('hhhh');
        formData.price=props.defaultPrice;
        updateState({
            defaultPrice:props.defaultPrice
        })

    },[props.defaultPrice])



    function beforeHandleChange(event,index){
        let key='showEmityTips'+(index+1)
        updateState({
            [key]:false
        })
        autoSetAllBidPrice(event,index,)
        if(index==1){
            setPriceItemPrice(event)
        }
        handleChange(event)
    }


    function setPriceItemPrice(e){
        updateState({
            defaultPrice:e.target.value
        })
        formData.price=e.target.value

    }


    function autoSetAllBidPrice(event,index) {

        if(index==0&&bidInfo){ //填写商品数量，更新总价，并且已经选择了商品
            let count=event.target.value;
            let pattern = /^[0-9]*$/;
            let _price=bidInfo.price||bidInfo.productPrice
            let price=parseInt(_price)||0;

           
            if(pattern.test(count)){
                let totalPrice=(count-0)*(price-0);
                if(totalPrice&&totalPrice>0){
                    // console.log(totalPrice)
                    formData.price=Filter.float(totalPrice,2);
                    formData.defaultprice=Filter.float(totalPrice,2);
                    updateState({
                        defaultPrice:Filter.float(totalPrice,2),
                    })
                }else{
                    // formData.price='';
                    formData.defaultprice=''
                    // updateState({
                    //     defaultPrice:'',
                    // })
                }
            }
        }

    }
    

    
    function handleChangeForText(txt) {
        formData.remark=txt;
    }


    addValidateMulti({count:[RobinFilter.numberValidate],price:[RobinFilter.priceValidate],day:[RobinFilter.numberValidate],});

    return(
        <div className={'zen_m-l-13'}>
            {
                (isEditPage||isSelected)?
                    <BidProInfo
                        bid={bidInfo}
                        onClick={showProductModal}
                    />
                    :
                    <ChoosePro
                        showProductModal={showProductModal}
                    />
            }

            <p className={'zen-fs-16 zen_0093EB zen_m-t-40 zen_m-b-30'}>填写报价信息</p>
            <form className={'zen_m-t-30'} name={'bidInputForm'}>
                <InputItem
                    name={'count'}
                    title={'竞价商品数量'}
                    tips={`由于不同供应商的商品包装规格不同，请按照采购入购买的商品数量，根据您的包装规格来填写竞价商品数量。`}
                    placeholder={'请输入'}
                    handleChange={(e)=>beforeHandleChange(e,0)}
                    formData={formData}
                    className={'bid-inputbid-label2-box'}
                    index={1}
                    unit={bidInfo&&bidInfo.unit}
                    showEmityTips={showEmityTips1}
                    emityTip={emityTipArr[0]}
                />
                <InputItem
                    name={'price'}
                    index={2}
                    title={'竞价总报价'}
                    tips={'竞价采用报总价的方式，报价金额不能超过总销售价。'}
                    placeholder={'请输入'}
                    handleChange={(e)=>beforeHandleChange(e,1)}
                    defaultPrice={stateObj.defaultPrice}
                    formData={formData}
                    className={'bid-inputbid-label4-box'}
                    unit={'元'}
                    showEmityTips={showEmityTips2}
                    emityTip={emityTipArr[1]}
                />
                <InputItem
                    name={'day'}
                    title={'发货天数'}
                    tips={'从中标日期开始，几天内送货。'}
                    placeholder={'请输入'}
                    handleChange={(e)=>beforeHandleChange(e,2)}
                    formData={formData}
                    className={'bid-inputbid-label-box'}
                    unit={'天'}
                    showEmityTips={showEmityTips3}
                    emityTip={emityTipArr[2]}
                />
                <TextAreaItem
                    // name={'remark'}
                    noStar={true}
                    isTextArea={true}
                    className={'bid-inputbid-label3-box'}
                    title={'我的优势'}
                    placeholder={'写一些优势，增加中标的可能性。'}
                    handleChange={(txt)=>handleChangeForText(txt)}
                    // formData={formData}
                />

                <AddFile
                    formData={formData}
                />

                <div
                    onClick={()=>{
                        let tipsArr=defaultEmiptyTips;
                        if(!formData.count){
                            updateState({showEmityTips1:true})
                        }
                        if(!formData.price){
                            updateState({showEmityTips2:true})
                        }
                        if(!formData.day){
                            updateState({showEmityTips3:true})
                        }
                        console.log(defaultPrice)
                        console.log((formData.defaultprice-0)-(defaultPrice-0))
                        if(formData.count&&defaultPrice&&((formData.defaultprice-0)-(defaultPrice-0)<0)){
                            updateState({showEmityTips2:true})
                            tipsArr[1]='竞价总报价不应大于商品总价'
                        }
                        updateState({emityTipArr:tipsArr});

                        showBIdAlertModal()
                    }}
                    className={'bid-inputbid-submit-btn'}>
                    提交报价
                </div>

            </form>
            <InfoModal
                content={modalMsg}
                getRef={v => (infoModal = v)}
                onConfrim={() => {

                }}
            />
        </div>
    )


    //提交报价弹窗    
    function showBIdAlertModal() {

        
        let productSn=null
        if(bidInfo){
            productSn=bidInfo.sn
        }

        if(!productSn){
            infoModal.showModal();
            return
        }

        if(!formData.count||!formData.price||!formData.day){
            return null;
        }

        if(formData.count&&defaultPrice&&((formData.defaultprice-0)-(defaultPrice-0)<0)){
            return
        }



        function closeModal(value) {
            modal.remove();
        }

        function Content(props) {
           return(
               <ConfirmPriceModal
                   bidInfo={bidInfo}
                   formData={formData}
                   clickOk={()=>{
                       saveOrUpdateBid(productSn,closeModal);
                   }}
                   clickCancel={closeModal}
                   closeModal={closeModal}
               />
           )
        }

        let options = {
            header: "确认报价",
            modalClass: "zen_bdr-5 bid-bidiput-zen-modal2 bid-confrim-price-modal",
            // footer: "test footer",
            content: Content,
            size: "md",
            hideFooter: true,
            // cbList: [closeModal],
            close: closeModal,
            closeByBackDrop: true
        };
        let modal = ZenModal.loadModal(options);
        modal.show();

        setTimeout(()=>{
            setModalBg();
        },0)
        
    }


    function saveOrUpdateBid(productSn,closeModal){

        let url=`/bid/order/suppbid/saveOrUpdateBid`;

        let params={
            attachmentUrl: formData.fileId,
            count: formData.count,
            deliveryTime: formData.day,
            itemId: $state.params&& $state.params.id,
            price: formData.price,
            productSn: productSn,
            remark: formData.remark
        }
        if(isEditPage){
            params={
                attachmentUrl: formData.fileId,
                id: bid.id,
                count: formData.count,
                deliveryTime: formData.day,
                itemId: $state.params&& $state.params.id,
                price: formData.price,
                productSn: productSn,
                remark: formData.remark
            }
        }


        // console.log(params);

        
        Rest.post(url,params)
            .then(res=>{
                console.log(res);
                if(res.resultCode=="0000"){
                    closeModal()
                    if(isEditPage){
                        let href=location.href;
                        let hrefpre=href.split('&isEdit')[0];
                        location.href=hrefpre;
                        location.reload();
                    }else{
                        location.reload();
                    }
                }
                else{
                    updateState({
                        modalMsg:res.msg
                    })
                    setTimeout(()=>{
                        infoModal.showModal();
                    },500)

                }
            })
            .catch(err=>{
               console.log(err);

            })
    }



    function chooseProduct(productSn) {
        let url=`/bid/order/suppbid/getProductInfo`;
        let params={
            sn: productSn
        };
        Rest.post(url,params)
            .then(res=>{
                console.log(res)
                if(res.resultCode=="3000"){
                    updateState({
                        modalMsg:res.msg
                    })
                    setTimeout(()=>{
                        infoModal.showModal();
                    },500)
                }
                else{
                    props.choose(res)
                }

            })
            .catch(err=>{
                console.log(err)
            })
    }


    function  showProductModal(){
        function closeModal(value) {
            modal.remove();
        }

        function Content(props) {
            return (
                <ModalContent
                    selected={(item)=>{
                        if(item.id){
                            chooseProduct(item.id);
                            closeModal();
                        }else{
                            infoModal.showModal();
                        }

                    }}
                    close={closeModal}
                />
            );
        }
        let options = {
            header: "选择商品",
            modalClass: "zen_bdr-5 bid-bidiput-zen-modal",
            content: Content,
            size: "md",
            hideFooter: true,
            // cbList: [closeModal],
            close: closeModal,
            closeByBackDrop: true
        };
        let modal = ZenModal.loadModal(options);

        modal.show();

        setTimeout(()=>{
            setModalBg();
        },0)

    }

    function setModalBg() {
        const zenModalWrap= document.querySelector('.zenModalWrap-backdrop');
        zenModalWrap.style.backgroundColor='rgba(0,0,0,0)';

        const zenModalWrapRoot=document.querySelector('.zenModalWrap');
        zenModalWrapRoot.style.zIndex=6;
    }

}


























